---
title: "Structured Output"
description: "Type-safe responses with Zod schema validation"
icon: "brackets-curly"
---

Structured output enables agents to return type-safe, validated data instead of plain text. By defining a Zod schema, you get automatic validation, type inference, and intelligent retry logic when data is incomplete.

## How Structured Output Works

When you provide a Zod schema to the agent:

1. **Schema awareness**: Agent understands exactly what data structure to return
2. **Automatic validation**: Responses are validated against your schema
3. **Type safety**: Full TypeScript type inference from your schema
4. **Intelligent retries**: Agent automatically gathers missing required fields
5. **Guaranteed structure**: You always get data matching your schema or an error

<Info>
**Zod Integration**: We use Zod for schema definition because it provides excellent TypeScript integration, runtime validation, and clear error messages.
</Info>

## Benefits

### Type Safety

Get full TypeScript types automatically inferred from your schema:

```typescript
const schema = z.object({
  name: z.string(),
  age: z.number()
})

const result = await agent.run(prompt, { schema })
// result.name is string
// result.age is number
```

### Automatic Retry

If the agent's first response is missing required fields, it automatically tries again to gather the missing information.

### Validation

Responses are validated at runtime, ensuring your code always receives correctly structured data.

## Basic Example

<CodeGroup>
```typescript TypeScript
import { z } from 'zod'
import { ChatOpenAI } from '@langchain/openai'
import { MCPAgent, MCPClient } from 'mcp-use'

// Define the schema using Zod
const WeatherInfo = z.object({
    city: z.string().describe('City name'),
    temperature: z.number().describe('Temperature in Celsius'),
    condition: z.string().describe('Weather condition'),
    humidity: z.number().describe('Humidity percentage')
})

// TypeScript type inferred from schema
type WeatherInfo = z.infer<typeof WeatherInfo>

async function main() {
    // Setup client and agent
    const client = new MCPClient({ mcpServers: {...} })
    const llm = new ChatOpenAI({ model: 'gpt-4o' })
    const agent = new MCPAgent({ llm, client })

    // Get structured output
    const weather = await agent.run(
        'Get the current weather in San Francisco',
        undefined, // maxSteps
        undefined, // manageConnector
        undefined, // externalHistory
        WeatherInfo // output schema
    )

    console.log(`Temperature in ${weather.city}: ${weather.temperature}°C`)
    console.log(`Condition: ${weather.condition}`)
    console.log(`Humidity: ${weather.humidity}%`)

    await client.closeAllSessions()
}

main().catch(console.error)
```

```typescript TypeScript
import { z } from 'zod'
import { ChatOpenAI } from '@langchain/openai'
import { MCPAgent, MCPClient } from 'mcp-use'

// Define the schema using Zod
const WeatherInfo = z.object({
    city: z.string().describe('City name'),
    temperature: z.number().describe('Temperature in Celsius'),
    condition: z.string().describe('Weather condition'),
    humidity: z.number().describe('Humidity percentage')
})

// TypeScript type inferred from schema
type WeatherInfo = z.infer<typeof WeatherInfo>

async function main() {
    // Setup client and agent
    const client = new MCPClient({ mcpServers: {...} })
    const llm = new ChatOpenAI({ model: 'gpt-4o' })
    const agent = new MCPAgent({ llm, client })

    // Get structured output
    const weather = await agent.run(
        'Get the current weather in San Francisco',
        undefined, // maxSteps
        undefined, // manageConnector
        undefined, // externalHistory
        WeatherInfo // output schema
    )

    console.log(`Temperature in ${weather.city}: ${weather.temperature}°C`)
    console.log(`Condition: ${weather.condition}`)
    console.log(`Humidity: ${weather.humidity}%`)

    await client.closeAllSessions()
}

main().catch(console.error)
```
</CodeGroup>

## Key Benefits

- **Type Safety**: Get Pydantic (Python) or Zod (TypeScript) models with full IDE support and validation
- **Intelligent Gathering**: Agent knows what information is required and won't stop until it has everything
- **Automatic Retry**: Missing fields trigger continued execution automatically
- **Field Validation**: Built-in validation for required fields, data types, and constraints

The agent will continue working until all required fields in your schema can be populated, ensuring you always get complete, structured data.
